<template>
  <div class="menu-permissions">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单权限管理</span>
          <el-button type="primary" @click="showAssignDialog = true">分配权限</el-button>
        </div>
      </template>

      <!-- 角色列表 -->
      <el-table :data="roles" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="菜单权限数量" width="120">
          <template #default="{ row }">
            <el-tag>{{ getMenuCount(row.id) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewRoleMenus(row)">查看权限</el-button>
            <el-button size="small" type="primary" @click="assignMenus(row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配菜单权限对话框 -->
    <el-dialog v-model="showAssignDialog" title="分配菜单权限" width="600px">
      <el-form label-width="100px">
        <el-form-item label="选择角色">
          <el-select v-model="selectedRoleId" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="menuTreeRef"
            :data="menuTree"
            show-checkbox
            node-key="id"
            :default-checked-keys="selectedMenuIds"
            :props="{ children: 'children', label: 'name' }"
            style="width: 100%"
          >
            <template #default="{ node, data }">
              <div class="menu-node">
                <el-icon v-if="data.icon">
                  <component :is="data.icon" />
                </el-icon>
                <span>{{ data.name }}</span>
              </div>
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAssignDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMenuPermissions" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查看角色菜单权限对话框 -->
    <el-dialog v-model="showViewDialog" title="角色菜单权限" width="500px">
      <div v-if="currentRole">
        <h4>{{ currentRole.name }} - 菜单权限</h4>
        <div v-if="currentRoleMenus.length > 0">
          <div v-for="menu in currentRoleMenus" :key="menu.id" class="menu-item">
            <el-tag style="margin: 2px;">
              <el-icon v-if="menu.icon" style="margin-right: 4px;">
                <component :is="menu.icon" />
              </el-icon>
              {{ menu.name }}
            </el-tag>
          </div>
        </div>
        <el-empty v-else description="该角色暂无菜单权限" :image-size="60" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { House, User, Monitor } from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const showAssignDialog = ref(false)
const showViewDialog = ref(false)
const roles = ref([])
const menuTree = ref([])
const selectedRoleId = ref(null)
const selectedMenuIds = ref([])
const currentRole = ref(null)
const currentRoleMenus = ref([])
const menuTreeRef = ref(null)

// 菜单权限统计
const menuPermissionCounts = ref({})

// 加载数据
const loadRoles = async () => {
  try {
    const response = await userManagementAPI.getRoles()
    roles.value = response.results || response
  } catch (error) {
    console.error('加载角色失败:', error)
    ElMessage.error('加载角色失败')
  }
}

const loadMenus = async () => {
  try {
    const response = await userManagementAPI.getMenus()
    menuTree.value = buildMenuTree(response.results || response)
  } catch (error) {
    console.error('加载菜单失败:', error)
    ElMessage.error('加载菜单失败')
  }
}

const loadMenuPermissionCounts = async () => {
  // 加载每个角色的菜单权限数量
  for (const role of roles.value) {
    try {
      const response = await userManagementAPI.getRoleMenus(role.id)
      menuPermissionCounts.value[role.id] = response.length
    } catch (error) {
      menuPermissionCounts.value[role.id] = 0
    }
  }
}

// 构建菜单树
const buildMenuTree = (menus) => {
  const menuMap = {}
  const rootMenus = []

  // 创建菜单映射
  menus.forEach(menu => {
    menuMap[menu.id] = { ...menu, children: [] }
  })

  // 构建树结构
  menus.forEach(menu => {
    if (menu.parent) {
      if (menuMap[menu.parent]) {
        menuMap[menu.parent].children.push(menuMap[menu.id])
      }
    } else {
      rootMenus.push(menuMap[menu.id])
    }
  })

  return rootMenus
}

// 获取菜单权限数量
const getMenuCount = (roleId) => {
  return menuPermissionCounts.value[roleId] || 0
}

// 查看角色菜单权限
const viewRoleMenus = async (role) => {
  currentRole.value = role
  try {
    const response = await userManagementAPI.getRoleMenus(role.id)
    currentRoleMenus.value = response.map(item => item.menu)
    showViewDialog.value = true
  } catch (error) {
    console.error('加载角色菜单失败:', error)
    ElMessage.error('加载角色菜单失败')
  }
}

// 分配菜单权限
const assignMenus = async (role) => {
  selectedRoleId.value = role.id
  try {
    const response = await userManagementAPI.getRoleMenus(role.id)
    selectedMenuIds.value = response.map(item => item.menu.id)
    showAssignDialog.value = true
  } catch (error) {
    console.error('加载角色菜单失败:', error)
    ElMessage.error('加载角色菜单失败')
  }
}

// 保存菜单权限
const saveMenuPermissions = async () => {
  if (!selectedRoleId.value) {
    ElMessage.warning('请选择角色')
    return
  }

  const checkedKeys = menuTreeRef.value.getCheckedKeys()
  
  saving.value = true
  try {
    await userManagementAPI.assignMenusToRole(selectedRoleId.value, { menu_ids: checkedKeys })
    ElMessage.success('菜单权限分配成功')
    showAssignDialog.value = false
    await loadMenuPermissionCounts()
  } catch (error) {
    console.error('分配菜单权限失败:', error)
    ElMessage.error('分配菜单权限失败')
  } finally {
    saving.value = false
  }
}

// 初始化
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([loadRoles(), loadMenus()])
    await loadMenuPermissionCounts()
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-node {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}



.menu-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
</style>
